package com.lw.demo;

import java.util.Random;

public class SumThreadDemo {

    private static double [] nums = new double[1_0000_0000];
    private static Random r  =  new Random();
    private static  double  result = 0.0,result1 = 0.0,result2 = 0.0,result3 = 0.0,result4 = 0.0;

    static {
        for (int i =0;i < nums.length ; i++){
            nums[i] = r.nextDouble();
        }
    }

    public static void main(String[] args) throws InterruptedException {
//        SumThreadDemo.m1();
        SumThreadDemo.m2();
    }

    /**
     * 使用单线程计算
     */
    private  static  void m1(){
        long startTime = System.currentTimeMillis();
        for (int i = 0;i < nums.length;i++){
            result += nums[i];
        }
        System.out.println(result);
        long endTime = System.currentTimeMillis();
        long countTime = endTime - startTime;
        System.out.println("单线程计算===m1耗时:"+countTime);//210
    }

    /**
     * 使用多线程计算
     */
    private  static  void m2() throws InterruptedException {


        Thread thread1 =   new Thread(()->{
            for (int i = 0;i < nums.length/2;i++){
                result1 += nums[i];
            }
        });

        Thread thread2 =   new Thread(()->{
            for (int i = nums.length/2;i < nums.length;i++){
                result2 += nums[i];
            }
        });
        Thread thread3 =   new Thread(()->{
            for (int i = nums.length/3;i < nums.length;i++){
                result3 += nums[i];
            }
        });
        Thread thread4 =   new Thread(()->{
            for (int i = nums.length/4;i < nums.length;i++){
                result4 += nums[i];
            }
        });
        long startTime = System.currentTimeMillis();
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(result1+ result2+ result3+ result4);
        long endTime = System.currentTimeMillis();
        long countTime = endTime - startTime;
        System.out.println("多线程计算===m2耗时:"+countTime);//116
    }



}